﻿namespace LeadMaster.Controllers
{
  using System;
  using System.Data.Entity;
  using System.Linq;
  using System.Web.Mvc;
  using LeadMaster.DAL;
  using LeadMaster.ViewModels;
  using System.Web.Security;
  using LeadMaster.Helpers;
  using System.Collections.Generic;
  using LeadMaster.Models;
  using System.Data;
  using LeadMaster.Properties;
  using System.Configuration;
  using System.Web;
  using System.IO;
  using System.Text;
  using System.Data.Entity.Core.Objects;
  using System.Globalization;

  [Authorize]
  public class OutsourcerController : Controller
  {

    private DunsmoreContext db = new DunsmoreContext();

      public ActionResult Index(bool isReleaseOnly=false)
      {
        ViewModelOutsourcer viewModel = new ViewModelOutsourcer();
        viewModel.viewModelPerson = SiteValues.FetchIntroInfo();
        int callCentreID = GetID();
        ViewBag.LeadClient = new SelectList(db.Leads
              .Join(db.PurchaseOrders, a => a.LeadID, b => b.LeadID, (a,b) => new { a,b })
              .Where(m => m.a.LeadID==m.b.LeadID)
              .Where(m => m.b.Visible == true)
              .Where(m => m.a.IntRef != null && m.a.IntRef.Length > 0)
              .Where(m => m.b.Paid == null || m.b.Paid == false)
              .Select(m => new {m.a.LeadID, m.a.Sector.Sector})
              .OrderBy(m => m.Sector)
              .Distinct()
            , "LeadID", "Sector");
        viewModel.LeadDate = DateTime.Now;
        viewModel.CallCentreID = callCentreID;
        viewModel.ReleaseToClientOnly = isReleaseOnly;
        return View(viewModel);
      }

      [HttpPost]
      public ActionResult Index(ViewModelOutsourcer viewModel, string LeadClient)
      {
        viewModel.Leads = db.Leads.Find(Convert.ToInt16(LeadClient));

        return RedirectToAction("FetchLeadBlock", viewModel);
      }

      public ActionResult EnterLeads()
      {
        try
        {
          int callCentreID = GetID();
          var clientList=db.Leads
              .Include(m => m.Sector)
              .Select(m => new {m.LeadID, m.Sector.Sector})
              .Distinct();
          ViewBag.LeadClient = new SelectList(clientList.OrderBy(m => m.Sector), "LeadID", "Sector");
          ViewBag.CallCentreID = callCentreID;
          return View();
        }
        catch (Exception e)
        {
          ViewBag.ErrorMessage = "Enter Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
          return View("Errormessages");
        }
      }

      [HttpPost]
      public ActionResult EnterLeads(ViewModelOutsourcer viewModel)
      {
        try
        {
          int callCentreID = viewModel.CallCentreID;
          viewModel.Leads = db.Leads.Where(m => m.LeadID == viewModel.LeadClient).FirstOrDefault();
          if (false && viewModel.Leads.StreetView == true)
          {
            string companyPostcode = viewModel.Leads.Company.Postcode.Replace(" ", "");
            PostCodes postCode = db.Postcodes.Where(m => m.Postcode == companyPostcode).FirstOrDefault();
            ViewBag.LatLong = string.Format("{0},{1}", postCode.lat.ToString(), postCode.longitude.ToString());
          }          
          viewModel.ListCompanyRegistered = db.CompanyRegistered.Where(c => c.CompanyID == viewModel.Leads.CompanyID).ToList();
          viewModel.ListCompanyRestrictions = db.CompanyRestriction.Where(c => c.CompanyID == viewModel.Leads.CompanyID).ToList();
          viewModel.ListCompanySundries = db.CompanySundries.Where(c => c.CompanyID == viewModel.Leads.CompanyID).ToList();
          viewModel.LeadTemplate = db.LeadTemplate.Where(c => c.LeadTemplateID == viewModel.Leads.LeadTemplateID).FirstOrDefault();
          viewModel.ListLeadStat = db.LeadStat.Where(l => l.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
          viewModel.ListLeadGroups = db.LeadGroups.Where(l => l.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
          viewModel.ListStatQuestions = db.LeadStatQuestions.Include(i => i.LeadStat).Where(w => w.LeadStat.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
          viewModel.ListGroupQuestions = db.LeadGroupQuestions.Include(i => i.LeadGroups).Where(w => w.LeadGroups.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
          viewModel.LeadQuestions = new List<questiontype>();
          int questionRow = 0;
          questiontype newQs;
          int questionOrder = 1;
          while (questionOrder!=99)
          {
            // Static Question Set ?
            if (db.LeadStat.Any(m => m.LeadTemplateID==viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder==questionOrder))
            {
              LeadStat item = db.LeadStat.Where(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder).FirstOrDefault();
              newQs = new questiontype();
              newQs.QuestionRow = questionRow;
              newQs.TheQuestion = string.Empty;
              newQs.TheAnswer = string.Empty;
              newQs.Mandatory = false;
              newQs.IsQuestionHeader = true;
              newQs.QuestionHeader = item.Title;
              newQs.Notes = item.Notes;
              newQs.DisplayOrder = item.DisplayOrder*100;
              viewModel.LeadQuestions.Add(newQs);
              questionRow++;
              foreach (var statitem in viewModel.ListStatQuestions.Where(m => m.LeadStatID == item.LeadStatID).OrderBy(m => m.DisplayOrder))
              {
                newQs = new questiontype();
                newQs.QuestionRow = questionRow;
                newQs.TheQuestion = statitem.Question;
                newQs.TheAnswer = string.Empty;
                newQs.Mandatory = statitem.Mandatory;
                newQs.QuestionType = statitem.AnswerType;
                newQs.Notes = statitem.Notes;
                newQs.AcceptedAnswerChar = statitem.AcceptedAnswerChar;
                newQs.AcceptedAnswerBool = statitem.AcceptedAnswerBool;
                newQs.AcceptedAnswerIntFrom = statitem.AcceptedAnswerIntFrom;
                newQs.AcceptedAnswerIntTo = statitem.AcceptedAnswerIntTo;
                newQs.LeadStatQuestionsID = statitem.LeadStatQuestionsID;
                newQs.DropDown = statitem.DropDown;
                newQs.DisplayOrder = item.DisplayOrder * 100 + statitem.DisplayOrder;
                viewModel.LeadQuestions.Add(newQs);
                questionRow++;
              }
              questionRow++;
            }
            else if (db.LeadGroups.Any(m => m.LeadTemplateID==viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder==questionOrder))
            {
              LeadGroups item = db.LeadGroups.Where(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder).FirstOrDefault();
              newQs = new questiontype();
              newQs.QuestionRow = questionRow;
              newQs.TheQuestion = string.Empty;
              newQs.TheAnswer = string.Empty;
              newQs.Mandatory = false;
              newQs.IsQuestionHeader = true;
              newQs.QuestionHeader = item.Title;
              newQs.QualifyingGroup = item.QualifyingGroup;
              newQs.MinMandatoryPrimary = item.MinMandatoryPrimary;
              newQs.MinMandatorySecondary = item.MinMandatorySecondary;
              newQs.LeadGroupsID = item.LeadGroupsID;
              newQs.Notes = item.Notes;
              newQs.DisplayOrder = item.DisplayOrder * 100;
              if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
              {
                newQs.SubHeader = "Two groups here. So we need at least " + item.MinMandatoryPrimary.ToString() + " in this group, and ...";
              }
              else if (item.MinMandatoryPrimary > 0)
              {
                newQs.SubHeader = "We need at least " + item.MinMandatoryPrimary.ToString() + " in this group to qualify.";
              }
              viewModel.LeadQuestions.Add(newQs);
              questionRow++;
              // Primary Group
              foreach (var groupitem in viewModel.ListGroupQuestions.Where(m => m.LeadGroupsID == item.LeadGroupsID).Where(m => m.PrimarySecondary == "P").OrderBy(m => m.DisplayOrder))
              {
                newQs = new questiontype();
                newQs.QuestionRow = questionRow;
                newQs.TheQuestion = groupitem.Question;
                newQs.TheAnswer = string.Empty;
                newQs.Mandatory = groupitem.Mandatory;
                newQs.QuestionType = groupitem.AnswerType;
                newQs.Notes = groupitem.Notes;
                newQs.DropDown = groupitem.DropDown;
                newQs.AcceptedAnswerChar = groupitem.AcceptedAnswerChar;
                newQs.AcceptedAnswerBool = groupitem.AcceptedAnswerBool;
                newQs.AcceptedAnswerIntFrom = groupitem.AcceptedAnswerIntFrom;
                newQs.AcceptedAnswerIntTo = groupitem.AcceptedAnswerIntTo;
                newQs.LeadGroupQuestionsID = groupitem.LeadGroupQuestionsID;
                newQs.DropDown = groupitem.DropDown;
                newQs.PrimarySecondary = "P";
                newQs.LeadGroupsID = item.LeadGroupsID;
                newQs.QualifyingGroup = item.QualifyingGroup;
                newQs.DisplayOrder = item.DisplayOrder * 100 + groupitem.DisplayOrder;
                viewModel.LeadQuestions.Add(newQs);
                questionRow++;
              }
              if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
              {
                newQs = new questiontype();
                newQs.QuestionRow = questionRow;
                newQs.TheQuestion = string.Empty;
                newQs.TheAnswer = string.Empty;
                newQs.Mandatory = false;
                newQs.IsQuestionHeader = true;
                newQs.QuestionHeader = item.Title;
                if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
                {
                  newQs.SubHeader = "... at least " + item.MinMandatorySecondary.ToString() + " in this group to qualify.";
                }
                viewModel.LeadQuestions.Add(newQs);
                questionRow++;
              }
              // Secondary Group
              foreach (var groupitem in viewModel.ListGroupQuestions.Where(m => m.LeadGroupsID == item.LeadGroupsID).Where(m => m.PrimarySecondary == "S").OrderBy(m => m.DisplayOrder))
              {
                newQs = new questiontype();
                newQs.QuestionRow = questionRow;
                newQs.TheQuestion = groupitem.Question;
                newQs.TheAnswer = string.Empty;
                newQs.Mandatory = groupitem.Mandatory;
                newQs.QuestionType = groupitem.AnswerType;
                newQs.Notes = groupitem.Notes;
                newQs.DropDown = groupitem.DropDown;
                newQs.PrimarySecondary = "S";
                newQs.AcceptedAnswerChar = groupitem.AcceptedAnswerChar;
                newQs.AcceptedAnswerBool = groupitem.AcceptedAnswerBool;
                newQs.AcceptedAnswerIntFrom = groupitem.AcceptedAnswerIntFrom;
                newQs.AcceptedAnswerIntTo = groupitem.AcceptedAnswerIntTo;
                newQs.LeadGroupQuestionsID = groupitem.LeadGroupQuestionsID;
                newQs.LeadGroupsID = item.LeadGroupsID;
                newQs.QualifyingGroup = item.QualifyingGroup;
                newQs.DisplayOrder = item.DisplayOrder * 100 + groupitem.DisplayOrder;
                viewModel.LeadQuestions.Add(newQs);
                questionRow++;
              }
              questionRow++;
            }    
            else
            {
              questionOrder = 98;
            }
            questionOrder++;
          }
          foreach (var item in viewModel.ListCompanyRegistered)
          {
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = item.LeadQuestion;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = item.MandatoryLeadQuestion;
            newQs.QuestionType = "L";
            newQs.Notes = item.Notes;
            newQs.CompanyRegisteredID = item.CompanyRegisteredID;
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
          }
          foreach (var item in viewModel.ListCompanyRestrictions)
          {
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = item.LeadQuestion;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = item.MandatoryLeadQuestion;
            newQs.QuestionType = "L";
            newQs.Notes = item.Notes;
            newQs.CompanyRestrictionsID = item.CompanyRestrictionsID;
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
          }
          if (viewModel.ListCompanySundries.Count()>0)
          {
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = string.Empty;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = false;
            newQs.IsQuestionHeader = true;
            newQs.QuestionHeader = "Client Specific Questions";
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
            foreach (var item in viewModel.ListCompanySundries)
            {
              newQs = new questiontype();
              newQs.QuestionRow = questionRow;
              newQs.TheQuestion = item.LeadQuestion;
              newQs.TheAnswer = string.Empty;
              newQs.Mandatory = item.MandatoryLeadQuestion;
              newQs.QuestionType = "L";
              newQs.CompanySundriesID=item.CompanySundriesID;
              viewModel.LeadQuestions.Add(newQs);
              questionRow++;
            }
          }
          return View("Questionnaire", viewModel);
        }
        catch (Exception e)
        {
          ViewBag.ErrorMessage = "Enter Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
          return View("Errormessages");
        }
      }

      [HttpPost]
      public ActionResult Questionnaire(ViewModelOutsourcer viewModel)
      {
        // check - can we really add a lead and possibly over supply
        int callCentreID = GetID();
        int? LeftToSupply = db.PurchaseOrders
            .Where(m => m.LeadID == viewModel.Leads.LeadID)
            .Where(m => m.Visible == true)
            .Where(m => m.Paid==null || m.Paid==false)
            .Select(m => m.Deficit)
            .Sum();
        if (LeftToSupply==null || LeftToSupply==0)
        {
            return View("NoneToSupply");
        }
        try
        {
          int nextBlockID = 0;
            if (db.LeadResults.Count()>0)
            {
              nextBlockID = (from l in db.LeadResults select l.BlockId).Max();  
            }
            nextBlockID++;
            string regionPostcode="";
            foreach (var item in viewModel.LeadQuestions)
            {
              viewModel.LeadResult = new LeadResults();
              viewModel.LeadResult.Question=item.TheQuestion;
              if (item.QuestionType=="L")
              {
                viewModel.LeadResult.Answer = item.TheAnswer=="true" ? "Yes" : "No" ;
              }
              else if (item.QuestionType == "C" && item.TheQuestion.ToLower().Contains("postcode"))
              {
                viewModel.LeadResult.Answer = item.TheAnswer.ToUpper();
              }
              else if (item.QuestionType == "C" && item.TheAnswer!=null)
              {
                viewModel.LeadResult.Answer = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(item.TheAnswer);
              }
              if (item.TheQuestion == "Postcode")
              {
                regionPostcode=viewModel.LeadResult.Answer.Substring(0,viewModel.LeadResult.Answer.IndexOfAny("0123456789".ToCharArray()));
              }
          
              viewModel.LeadResult.LeadID=viewModel.Leads.LeadID;
              viewModel.LeadResult.LeadDate = DateTime.Now;
              viewModel.LeadResult.CallCentreID = viewModel.CallCentreID;
              viewModel.LeadResult.QuestionBlock = viewModel.LeadQuestions.Count();
              viewModel.LeadResult.BlockId = nextBlockID;
              viewModel.LeadResult.LeadStatQuestionsID = item.LeadStatQuestionsID;
              viewModel.LeadResult.LeadGroupQuestionsID = item.LeadGroupQuestionsID;
              viewModel.LeadResult.CompanyRegisteredID = item.CompanyRegisteredID;
              viewModel.LeadResult.CompanyRestrictionsID = item.CompanyRestrictionsID;
              viewModel.LeadResult.CompanySundriesID = item.CompanySundriesID;
              viewModel.LeadResult.DisplayOrder = item.DisplayOrder;
          
              db.LeadResults.Add(viewModel.LeadResult);
            }
            LeadStatus leadStatus = new LeadStatus();
            leadStatus.LeadFlagsID = 1;
            leadStatus.LeadReasonsID = 1;
            leadStatus.LeadID = viewModel.Leads.LeadID;
            leadStatus.Lead=db.Leads.Find(viewModel.Leads.LeadID);
            leadStatus.BlockID = nextBlockID;
            leadStatus.UserID = (Guid)Membership.GetUser().ProviderUserKey;
            leadStatus.CallCentreID = viewModel.CallCentreID;
            leadStatus.ClassificationID = db.Classification.Where(m => m.CallCentreID == viewModel.CallCentreID && m.SectorID == leadStatus.Lead.SectorID).FirstOrDefault().ClassificationID;
            leadStatus.LeadDate = DateTime.Now;
            leadStatus.lastupdated = DateTime.Now;
            leadStatus.RegionPostcode = regionPostcode;
            leadStatus.FreePaid = viewModel.LeadQuestions.Where(m => m.TheAnswer == "Paid" || m.TheAnswer=="Free").FirstOrDefault().TheAnswer;
            db.LeadStatus.Add(leadStatus);
            db.SaveChanges();

            return RedirectToAction("FetchLeadBlock", new { viewModel = viewModel, leadID = viewModel.Leads.LeadID, immediateReview = true, ReleaseToClientOnly=true });
        }
        catch (Exception e)
        {
            ViewBag.ErrorMessage = "Enter Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
            return View("Errormessages");
        }

      }

      private int GetID()
      {
        Guid currentUser = (Guid)Membership.GetUser().ProviderUserKey;
        string currentUserName = db.Users.Where(m => m.UserID == currentUser).FirstOrDefault().UserName;
        int callCentreID = db.CallCentres
          .Where(m => m.UserName == currentUserName)
          .Select(m => m.CallCentreID)
          .FirstOrDefault();

        return callCentreID;
      }

      public void ReturnedLeads()
      {

      }

      public ActionResult ChangeLeadStatus(int id)
      {
 
        LeadResults leadResult = db.LeadResults.Find(id);
        LeadStatus leadStatus = db.LeadStatus.Where(m => m.LeadID == leadResult.LeadID && m.BlockID == leadResult.BlockId).FirstOrDefault();
        if (Roles.GetRolesForUser(User.Identity.Name).Contains(ApplicationRoles.Outsourcer))
        {
            ViewBag.LeadFlagsID = new SelectList(db.LeadFlags.Where(m => m.WithOSQC == true), "LeadFlagsID", "Description");
        }
     
        ViewBag.LeadResultsID = id;
        return PartialView(leadStatus);
      }

      [HttpPost]
      public ActionResult ChangeLeadStatus(LeadStatus leadStatus)
      {
        return RedirectToAction("SaveLeadStatus", leadStatus);
      }

      public ActionResult ReleaseToClient(int id, bool immediateReview=false)
      {
        LeadStatus leadStatus = db.LeadStatus.Find(id);
        // check - can we really add a lead and possibly over supply
        int callCentreID = GetID();
        leadStatus.LeadFlagsID = 23;
        leadStatus.LeadDate = DateTime.Now;
        leadStatus.CallCentreID = GetID();
        leadStatus.Notes = leadStatus.OutsourcerNotes;
        List<LeadResults> llr = db.LeadResults.Where(m => m.BlockId == leadStatus.BlockID).ToList();
        foreach (LeadResults item in llr)
        {
          item.LeadDate = DateTime.Now;
          db.Entry(item).State = EntityState.Modified;
        }
        int POCallCentreID=leadStatus.CallCentreID??0;
        db.Entry(leadStatus).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("SaveLeadStatus", new { leadStatusID = leadStatus.LeadStatusID, immediateReview = immediateReview });
      }

      public ActionResult SaveLeadStatus(int leadStatusID, bool immediateReview = false)
      {
        LeadStatus leadStatus = db.LeadStatus.Find(leadStatusID);
        ViewModelOutsourcer viewModel = new ViewModelOutsourcer();
        
        // has client asked for email notification ?
        Leads lead = db.Leads.Find(leadStatus.LeadID);
        if (lead.NewLeadAlert == true)
        {
            OracMailMessage mm = new OracMailMessage();
            List<LeadResults> lrs = db.LeadResults.Where(m => m.LeadID == leadStatus.LeadID && m.BlockId == leadStatus.BlockID).ToList();
            List<Contacts> recipients = db.Contacts
                            .Join(db.Companies, a => a.CompanyID, b => b.CompanyID, (a, b) => new { a, b })
                            .Where(m => m.a.CompanyID == m.b.CompanyID)
                            .Where(m => m.a.CompanyID == lead.CompanyID)
                            .Select(m => m.a)
                            .ToList();

            mm.EmailSubject = "A lead has just been uploaded under the reference " + lead.IntRef;

            string LeadDetails = string.Format("{0}", Environment.NewLine);
            LeadDetails += string.Format("Lead Details{0}", Environment.NewLine);
            LeadDetails += string.Format("{0}", Environment.NewLine);
            foreach (var item in lrs)
            {
                if (item.Answer != null)
                {
                    LeadDetails += string.Format("{0} - {1}{2}", item.Question, item.Answer ?? string.Empty, Environment.NewLine);
                    LeadDetails += (item.Question + item.Answer).Length > 30 ? Environment.NewLine : string.Empty;
                }
            }
            LeadDetails += string.Format("{0}", Environment.NewLine);
            LeadDetails += string.Format("{0}This is an automated email from Orac, please do not Reply. Please tell Orac the status of this lead after you have processed it. Thank you.", Environment.NewLine);

            // Send to Dunsmore internal QC
            if (leadStatus.LeadFlagsID==10)
            {
                mm.EmailTo = "karl@dunsmoremarketing.co.uk";
                mm.EmailBody = string.Format("Please can you qualify this lead as soon as possible{0}", Environment.NewLine);
                mm.EmailBody += LeadDetails;
                mm.SendEmail();
            }
            else
            {
                // send to each contact who want notification
                foreach (Contacts contact in recipients)
                {
                    if (contact.Email != null && contact.LLN == true)
                    {
                        mm.EmailTo = contact.Email;
                        mm.EmailBody = string.Format("Hello " + contact.Forename + ", greetings from Orac.{0}", Environment.NewLine);
                        mm.EmailBody += string.Format("Please contact this lead as soon as possible as they have just been qualified as a possible candidate for your scheme.{0}", Environment.NewLine);
                        mm.EmailBody += string.Format("{0}", Environment.NewLine);
                        mm.EmailBody += LeadDetails;
                        mm.SendEmail();
                    }
                }
            }
        }
        
        viewModel.LeadStatus = leadStatus;
        viewModel.Leads = db.Leads.Find(leadStatus.LeadID);
        viewModel.LeadClient = leadStatus.LeadID;
        viewModel.LeadDate = db.LeadResults
            .Where(m => m.LeadID == viewModel.LeadStatus.LeadID && m.BlockId == viewModel.LeadStatus.BlockID)
            .Select(m => m.LeadDate)
            .FirstOrDefault();
        viewModel.CallCentreID = GetID();
        return RedirectToAction("FetchLeadBlock", new { viewModel=viewModel, leadID=leadStatus.LeadID, immediateReview=immediateReview, ReleaseToClientOnly=true });
      }

      public ActionResult ChangeLeadReason(int id)
      {
        LeadResults leadResult = db.LeadResults.Find(id);
        LeadStatus leadStatus = db.LeadStatus.Where(m => m.LeadID==leadResult.LeadID && m.BlockID==leadResult.BlockId).FirstOrDefault();
        if (Roles.GetRolesForUser(User.Identity.Name).Contains(ApplicationRoles.Outsourcer))
        {
          ViewBag.LeadReasons = db.LeadReasons.Where(m => m.OSReasons == true).ToList();
        }
        return PartialView(leadStatus);
      }

      [HttpPost]
      public ActionResult ChangeLeadReason(LeadStatus leadStatus)
      {
          ViewModelOutsourcer viewModel = new ViewModelOutsourcer();

          if (ModelState.IsValid)
          {
              db.Entry(leadStatus).State = EntityState.Modified;
              db.SaveChanges();

              viewModel.LeadStatus = leadStatus;
              viewModel.LeadClient = leadStatus.LeadID;
              viewModel.Leads = db.Leads.Find(leadStatus.LeadID);
              viewModel.LeadDate = db.LeadResults
                .Where(m => m.LeadID == viewModel.LeadStatus.LeadID && m.BlockId == viewModel.LeadStatus.BlockID)
                .Select(m => m.LeadDate)
                .FirstOrDefault();
          }
        return RedirectToAction("FetchLeadBlock", viewModel);
      }

      public ActionResult ChangeOsNote(int id, bool immediateReview=false)
      {
        LeadStatus leadStatus = db.LeadStatus.Find(id);
        ViewBag.ImmediateReview = immediateReview;
        return PartialView(leadStatus);
      }

      [HttpPost]
      public ActionResult ChangeOsNote(LeadStatus leadStatus, bool immediateReview=false)
      {
        ViewModelOutsourcer viewModel = new ViewModelOutsourcer();

        if (ModelState.IsValid)
        {
          LeadStatus ls = db.LeadStatus.Find(leadStatus.LeadStatusID);
          ls.OutsourcerNotes = leadStatus.OutsourcerNotes;
          db.Entry(ls).State = EntityState.Modified;
          db.SaveChanges();

          viewModel.LeadStatus = ls;
          viewModel.LeadClient = ls.LeadID;
          viewModel.Leads = db.Leads.Find(ls.LeadID);
          viewModel.LeadDate = db.LeadResults
            .Where(m => m.LeadID == viewModel.LeadStatus.LeadID && m.BlockId == viewModel.LeadStatus.BlockID)
            .Select(m => m.LeadDate)
            .FirstOrDefault();
        }
        viewModel.CallCentreID = GetID();
        return RedirectToAction("FetchLeadBlock", new { viewModel=viewModel,leadid=viewModel.Leads.LeadID, immediateReview=immediateReview });
      }

    
    public ActionResult ReturnedLeads(ViewModelOutsourcer viewModel)
    {
      viewModel.Leads = db.Leads.Where(m => m.LeadID == viewModel.LeadClient).FirstOrDefault();
      int id = GetID();
      List<LeadResults> leadResults = db.LeadResults
        .Join(db.LeadStatus, a => a.LeadID, b => b.LeadID, (a, b) => new { a, b })
        .Where(m => m.a.LeadID == m.b.LeadID && m.a.BlockId == m.b.BlockID && m.b.LeadFlag.WithOSQC != null && m.b.LeadFlagsID>2)
        .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
        .Where(m => m.a.CallCentreID == id)
        .Where(m => m.a.LeadDate.Year == viewModel.LeadDate.Year && m.a.LeadDate.Month == viewModel.LeadDate.Month && m.a.LeadDate.Day == viewModel.LeadDate.Day)
        .OrderByDescending(m => m.a.BlockId)
        .ThenBy(m => m.a.DisplayOrder)
        .Select(m => m.a)
        .OfType<LeadResults>()
        .ToList();

      int blockID = 0;
      LeadStatus statusBlock = db.LeadStatus.FirstOrDefault();
      LeadFlags leadFlag = db.LeadFlags.FirstOrDefault();
      LeadReasons leadReason = db.LeadReasons.FirstOrDefault();
      viewModel.FullListLeadResults = new List<ListLeadResults>();
      int totalLeads = 0;
      foreach (LeadResults item in leadResults)
      {
        ListLeadResults listLeadResults = new ListLeadResults();
        listLeadResults.LeadResult = item;
        if (item.BlockId != blockID)
        {
          statusBlock = db.LeadStatus
              .Where(m => m.LeadID == item.LeadID && m.BlockID == item.BlockId)
              .FirstOrDefault();
          leadFlag = db.LeadFlags.Find(statusBlock.LeadFlagsID);
          leadReason = db.LeadReasons.Find(statusBlock.QCLeadReasonsID);

          totalLeads++;
        }
        blockID = item.BlockId;
        listLeadResults.LeadFlag = leadFlag;
        listLeadResults.LeadReason = leadReason;
        listLeadResults.LeadStatus = statusBlock;
        viewModel.FullListLeadResults.Add(listLeadResults);
      }
      // Title Generation for the table
      viewModel.Titles = new List<string>();
      if (viewModel.FullListLeadResults.Count() > 0)
      {
        int questionCounter = 0;
        foreach (var item in leadResults)
        {
          viewModel.Titles.Add(item.Question);
          questionCounter++;
          if (questionCounter == item.QuestionBlock)
          {
            questionCounter = 0;
            break;
          }
        }
      }
      ViewBag.TotalLeads = totalLeads;
      ViewBag.ReturnDate = viewModel.LeadDate.AddDays(4).ToShortDateString();
      return View("FetchLeadBlock",viewModel);
    }

    public ActionResult EditLeads(int leadID, int blockID, string caption="")
    {
      try
      {
        ViewModelOutsourcer viewModel = new ViewModelOutsourcer();
        viewModel.Leads = db.Leads.Where(m => m.LeadID == leadID).FirstOrDefault();
        viewModel.ListCompanyRegistered = db.CompanyRegistered.Where(c => c.CompanyID == viewModel.Leads.CompanyID).ToList();
        viewModel.ListCompanyRestrictions = db.CompanyRestriction.Where(c => c.CompanyID == viewModel.Leads.CompanyID).ToList();
        viewModel.ListCompanySundries = db.CompanySundries.Where(c => c.CompanyID == viewModel.Leads.CompanyID).ToList();
        viewModel.LeadTemplate = db.LeadTemplate.Where(c => c.LeadTemplateID == viewModel.Leads.LeadTemplateID).FirstOrDefault();
        viewModel.ListLeadStat = db.LeadStat.Where(l => l.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
        viewModel.ListLeadGroups = db.LeadGroups.Where(l => l.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
        viewModel.ListStatQuestions = db.LeadStatQuestions.Include(i => i.LeadStat).Where(w => w.LeadStat.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
        viewModel.ListGroupQuestions = db.LeadGroupQuestions.Include(i => i.LeadGroups).Where(w => w.LeadGroups.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
        viewModel.LeadQuestions = new List<questiontype>();
        viewModel.BlockID = blockID;
        List<LeadResults> leadResults = db.LeadResults.Where(m => m.LeadID == leadID && m.BlockId == blockID).ToList();
        int questionRow = 0;
        questiontype newQs;
        int questionOrder = 1;
        while (questionOrder != 99)
        {
          // Static Question Set ?
          if (db.LeadStat.Any(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder))
          {
            LeadStat item = db.LeadStat.Where(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder).FirstOrDefault();
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = string.Empty;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = false;
            newQs.IsQuestionHeader = true;
            newQs.QuestionHeader = item.Title;
            newQs.Notes = item.Notes;
            newQs.DisplayOrder = item.DisplayOrder * 100;
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
            foreach (var statitem in viewModel.ListStatQuestions.Where(m => m.LeadStatID == item.LeadStatID).OrderBy(m => m.DisplayOrder))
            {
              newQs = new questiontype();
              newQs.QuestionRow = questionRow;
              newQs.TheQuestion = statitem.Question;
              newQs.TheAnswer = leadResults.Where(m => m.LeadStatQuestionsID == statitem.LeadStatQuestionsID).Select(m => m.Answer).FirstOrDefault();
              newQs.Mandatory = statitem.Mandatory;
              newQs.QuestionType = statitem.AnswerType;
              newQs.Notes = statitem.Notes;
              newQs.AcceptedAnswerChar = statitem.AcceptedAnswerChar;
              newQs.AcceptedAnswerBool = statitem.AcceptedAnswerBool;
              newQs.AcceptedAnswerIntFrom = statitem.AcceptedAnswerIntFrom;
              newQs.AcceptedAnswerIntTo = statitem.AcceptedAnswerIntTo;
              newQs.LeadStatQuestionsID = statitem.LeadStatQuestionsID;
              newQs.DropDown = statitem.DropDown;
              newQs.DisplayOrder = item.DisplayOrder * 100 + statitem.DisplayOrder;
              viewModel.LeadQuestions.Add(newQs);
              questionRow++;
            }
            questionRow++;
          }
          else if (db.LeadGroups.Any(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder))
          {
            LeadGroups item = db.LeadGroups.Where(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder).FirstOrDefault();
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = string.Empty;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = false;
            newQs.IsQuestionHeader = true;
            newQs.QuestionHeader = item.Title;
            newQs.QualifyingGroup = item.QualifyingGroup;
            newQs.MinMandatoryPrimary = item.MinMandatoryPrimary;
            newQs.MinMandatorySecondary = item.MinMandatorySecondary;
            newQs.LeadGroupsID = item.LeadGroupsID;
            newQs.Notes = item.Notes;
            newQs.DisplayOrder = item.DisplayOrder * 100;
            if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
            {
              newQs.SubHeader = "Two groups here. So we need at least " + item.MinMandatoryPrimary.ToString() + " in this group, and ...";
            }
            else if (item.MinMandatoryPrimary > 0)
            {
              newQs.SubHeader = "We need at least " + item.MinMandatoryPrimary.ToString() + " in this group to qualify.";
            }
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
            // Primary Group
            foreach (var groupitem in viewModel.ListGroupQuestions.Where(m => m.LeadGroupsID == item.LeadGroupsID).Where(m => m.PrimarySecondary == "P").OrderBy(m => m.DisplayOrder))
            {
              newQs = new questiontype();
              newQs.QuestionRow = questionRow;
              newQs.TheQuestion = groupitem.Question;
              newQs.TheAnswer = leadResults.Where(m => m.LeadGroupQuestionsID == groupitem.LeadGroupQuestionsID).Select(m => m.Answer).FirstOrDefault();
              newQs.Mandatory = groupitem.Mandatory;
              newQs.QuestionType = groupitem.AnswerType;
              newQs.Notes = groupitem.Notes;
              newQs.DropDown = groupitem.DropDown;
              newQs.AcceptedAnswerChar = groupitem.AcceptedAnswerChar;
              newQs.AcceptedAnswerBool = groupitem.AcceptedAnswerBool;
              newQs.AcceptedAnswerIntFrom = groupitem.AcceptedAnswerIntFrom;
              newQs.AcceptedAnswerIntTo = groupitem.AcceptedAnswerIntTo;
              newQs.LeadGroupQuestionsID = groupitem.LeadGroupQuestionsID;
              newQs.DropDown = groupitem.DropDown;
              newQs.PrimarySecondary = "P";
              newQs.LeadGroupsID = item.LeadGroupsID;
              newQs.QualifyingGroup = item.QualifyingGroup;
              newQs.DisplayOrder = item.DisplayOrder * 100 + groupitem.DisplayOrder;
              viewModel.LeadQuestions.Add(newQs);
              questionRow++;
            }
            if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
            {
              newQs = new questiontype();
              newQs.QuestionRow = questionRow;
              newQs.TheQuestion = string.Empty;
              newQs.TheAnswer = string.Empty;
              newQs.Mandatory = false;
              newQs.IsQuestionHeader = true;
              newQs.QuestionHeader = item.Title;
              if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
              {
                newQs.SubHeader = "... at least " + item.MinMandatorySecondary.ToString() + " in this group to qualify.";
              }
              viewModel.LeadQuestions.Add(newQs);
              questionRow++;
            }
            // Secondary Group
            foreach (var groupitem in viewModel.ListGroupQuestions.Where(m => m.LeadGroupsID == item.LeadGroupsID).Where(m => m.PrimarySecondary == "S").OrderBy(m => m.DisplayOrder))
            {
              newQs = new questiontype();
              newQs.QuestionRow = questionRow;
              newQs.TheQuestion = groupitem.Question;
              newQs.TheAnswer = leadResults.Where(m => m.LeadGroupQuestionsID == groupitem.LeadGroupQuestionsID).Select(m => m.Answer).FirstOrDefault();
              newQs.Mandatory = groupitem.Mandatory;
              newQs.QuestionType = groupitem.AnswerType;
              newQs.Notes = groupitem.Notes;
              newQs.DropDown = groupitem.DropDown;
              newQs.PrimarySecondary = "S";
              newQs.AcceptedAnswerChar = groupitem.AcceptedAnswerChar;
              newQs.AcceptedAnswerBool = groupitem.AcceptedAnswerBool;
              newQs.AcceptedAnswerIntFrom = groupitem.AcceptedAnswerIntFrom;
              newQs.AcceptedAnswerIntTo = groupitem.AcceptedAnswerIntTo;
              newQs.LeadGroupQuestionsID = groupitem.LeadGroupQuestionsID;
              newQs.LeadGroupsID = item.LeadGroupsID;
              newQs.QualifyingGroup = item.QualifyingGroup;
              newQs.DisplayOrder = item.DisplayOrder * 100 + groupitem.DisplayOrder;
              viewModel.LeadQuestions.Add(newQs);
              questionRow++;
            }
            questionRow++;
          }
          else
          {
            questionOrder = 98;
          }
          questionOrder++;
        }
        foreach (var item in viewModel.ListCompanyRegistered)
        {
          newQs = new questiontype();
          newQs.QuestionRow = questionRow;
          newQs.TheQuestion = item.LeadQuestion;
          newQs.TheAnswer = leadResults.Where(m => m.CompanyRegisteredID == item.CompanyRegisteredID).Select(m => m.Answer).FirstOrDefault();
          newQs.Mandatory = item.MandatoryLeadQuestion;
          newQs.QuestionType = "L";
          newQs.Notes = item.Notes;
          newQs.CompanyRegisteredID = item.CompanyRegisteredID;
          viewModel.LeadQuestions.Add(newQs);
          questionRow++;
        }
        foreach (var item in viewModel.ListCompanyRestrictions)
        {
          newQs = new questiontype();
          newQs.QuestionRow = questionRow;
          newQs.TheQuestion = item.LeadQuestion;
          newQs.TheAnswer = leadResults.Where(m => m.CompanyRestrictionsID == item.CompanyRestrictionsID).Select(m => m.Answer).FirstOrDefault();
          newQs.Mandatory = item.MandatoryLeadQuestion;
          newQs.QuestionType = "L";
          newQs.Notes = item.Notes;
          newQs.CompanyRestrictionsID = item.CompanyRestrictionsID;
          viewModel.LeadQuestions.Add(newQs);
          questionRow++;
        }
        if (viewModel.ListCompanySundries.Count() > 0)
        {
          newQs = new questiontype();
          newQs.QuestionRow = questionRow;
          newQs.TheQuestion = string.Empty;
          newQs.TheAnswer = string.Empty;
          newQs.Mandatory = false;
          newQs.IsQuestionHeader = true;
          newQs.QuestionHeader = "Client Specific Questions";
          viewModel.LeadQuestions.Add(newQs);
          questionRow++;
          foreach (var item in viewModel.ListCompanySundries)
          {
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = item.LeadQuestion;
            newQs.TheAnswer = leadResults.Where(m => m.CompanySundriesID == item.CompanySundriesID).Select(m => m.Answer).FirstOrDefault();
            newQs.Mandatory = item.MandatoryLeadQuestion;
            newQs.QuestionType = "L";
            newQs.CompanySundriesID = item.CompanySundriesID;
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
          }
        }
        viewModel.LeadStatus = db.LeadStatus.Where(m => m.LeadID==leadID && m.BlockID==blockID).FirstOrDefault();
        if (caption!=string.Empty && caption.IndexOf("Dunsmore Notes")!=-1)
        {
            viewModel.LeadStatus.Notes += "\n" + DateTime.Now.ToShortDateString() + ": LEAD HAS BEEN REFRESHED\n";
            viewModel.LeadStatus.LeadDate = DateTime.Now;
            viewModel.LeadStatus.LeadFlagsID = 10;
        }
        db.Entry(viewModel.LeadStatus).State = EntityState.Modified;
        db.SaveChanges();
        viewModel.PurchaseOrders = new SelectList(db.PurchaseOrders.Where(m => m.LeadID == viewModel.Leads.LeadID), "PurchaseOrderID", "PID");
        return View("EditQuestionnaire", viewModel);
      }
      catch (Exception e)
      {
        ViewBag.ErrorMessage = "Edit Leads Questionnaire " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
        return View("Errormessages");
      }
    }

    [HttpPost]
    public ActionResult EditQuestionnaire(ViewModelOutsourcer viewModel)
    {
      try
      {
        int nextBlockID = viewModel.BlockID;
        string regionPostcode="";
        foreach (var item in viewModel.LeadQuestions)
        {
          viewModel.LeadResult = db.LeadResults
            .Where(m => m.LeadID == viewModel.Leads.LeadID)
            .Where(m => m.BlockId == viewModel.BlockID)
            .Where(m => m.Question == item.TheQuestion)
            .FirstOrDefault();
          if (viewModel.LeadResult!=null)
          {
            if (item.QuestionType == "L")
            {
              viewModel.LeadResult.Answer = item.TheAnswer == "true" ? "Yes" : "No";
            }
            else if (item.QuestionType == "C" && item.TheQuestion.ToLower().Contains("postcode"))
            {
              viewModel.LeadResult.Answer = item.TheAnswer.ToUpper();
            }
            else if (item.QuestionType == "C" && item.TheAnswer!=null)
            {
              viewModel.LeadResult.Answer = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(item.TheAnswer);
            }
            else if (item.QuestionType == "I")
            {
              viewModel.LeadResult.Answer = item.TheAnswer;
            }
            if (item.TheQuestion == "Postcode")
            {
              regionPostcode = viewModel.LeadResult.Answer.Substring(0, viewModel.LeadResult.Answer.IndexOfAny("0123456789".ToCharArray()) );
            }

          }
        }
        db.Entry(viewModel.LeadResult).State = EntityState.Modified;
        int? holdingPurchaseOrderID = viewModel.LeadStatus.PurchaseOrderID;
        viewModel.LeadStatus = db.LeadStatus.Where(m => m.LeadID == viewModel.Leads.LeadID && m.BlockID == viewModel.BlockID).FirstOrDefault();
        if (holdingPurchaseOrderID!=null)
        {
            viewModel.LeadStatus.PurchaseOrderID = holdingPurchaseOrderID;
        }
        viewModel.LeadStatus.LeadFlagsID = 1;
        viewModel.LeadStatus.UserID = (Guid)Membership.GetUser().ProviderUserKey;
        viewModel.LeadStatus.RegionPostcode = regionPostcode;
        db.Entry(viewModel.LeadStatus).State = EntityState.Modified;

        db.SaveChanges();
        viewModel.ReleaseToClientOnly = true;
        return RedirectToAction("FetchLeadBlock", new { viewModel = viewModel, leadID = viewModel.Leads.LeadID, immediateReview = true, surname = "", telephone = "", postcode = "", dayfilter = "", ReleaseToClientOnly = true });
      }
      catch (Exception e)
      {
        ViewBag.ErrorMessage = "Enter Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
        return View("Errormessages");
      }

    }


    public ActionResult FetchLeadBlock(ViewModelOutsourcer viewModel, int leadID = 0, bool immediateReview = false, string surname = "", string telephone = "", string postcode = "", string dayfilter = "", bool ReleaseToClientOnly = false, string leadref = "", string leadFilter = "")
    {
        ViewBag.ImmediateReview = immediateReview;
        if (immediateReview)
        {
          viewModel = new ViewModelOutsourcer();
          viewModel.Leads = db.Leads.Where(m => m.LeadID == leadID).FirstOrDefault();
        }
        else if (viewModel != null)
        {
          viewModel.Leads = db.Leads.Where(m => m.LeadID == viewModel.LeadClient).FirstOrDefault();
          ViewBag.LeadID = viewModel.LeadClient;
        }
        else
        {
          viewModel = new ViewModelOutsourcer();
          viewModel.Leads = db.Leads.Find(leadID);
          ViewBag.LeadID = leadID;
          viewModel.ReleaseToClientOnly = ReleaseToClientOnly;
        }

        
        ViewBag.LeadID = viewModel.Leads.LeadID;
        ViewBag.CallCentreID = viewModel.CallCentreID;
        ViewBag.surname = surname;
        ViewBag.telephone = telephone;
        ViewBag.postcode = postcode;
        ViewBag.dayFilter = dayfilter;
        ViewBag.FiltersSelected = !(string.IsNullOrEmpty(surname) && string.IsNullOrEmpty(telephone) && string.IsNullOrEmpty(postcode) && dayfilter == "" && string.IsNullOrEmpty(leadref));
        ViewBag.releaseOnly = viewModel.ReleaseToClientOnly;
        ViewBag.leadref = leadref;
        ViewBag.leadfilter = leadFilter;
        return View();
    }

    [HttpPost]
    public ActionResult RefreshFetchLeadBlock(ViewModelOutsourcer viewModel, string surname = "", string telephone = "", string postcode = "", string dayfilter = "",string leadref="", string leadFilter="")
    {
      return RedirectToAction("FetchLeadBlock", new {viewModel=viewModel,leadID=viewModel.LeadClient, immediateReview=false, surname=surname, telephone=telephone, postcode=postcode, dayfilter=dayfilter,leadref=leadref,leadFilter=leadFilter});
    }

    public ActionResult ShowLeadsByDate(int id, bool immediateReview, int callCentreID, string surname = "", string telephone = "", string postcode = "", string dayfilter = "", bool releaseOnly = false, string leadref = "", string leadFilter = "")
    {
      int testrecs = 0;
      int introducerID = GetID();
      try
      {
        ViewModelOutsourcer viewModel = new ViewModelOutsourcer();
        ViewBag.ImmmediateReview = immediateReview;
        ViewBag.ReleaseOnly = releaseOnly;
        ViewBag.FiltersSelected = !(string.IsNullOrEmpty(surname) && string.IsNullOrEmpty(telephone) && string.IsNullOrEmpty(postcode) && dayfilter=="" && string.IsNullOrEmpty(leadref));
        int blockID = 0;
        if (immediateReview==false && string.IsNullOrEmpty(surname) && string.IsNullOrEmpty(telephone) && string.IsNullOrEmpty(postcode) && dayfilter=="" && string.IsNullOrEmpty(leadref) && releaseOnly==false)
        {
          return PartialView("PartialShowLeads", viewModel);
        }
        ViewBag.FiltersSelected = true;
        viewModel.Leads = db.Leads.Where(m => m.LeadID == id).FirstOrDefault();
        
        List<LeadResults> leadResults;
        if (immediateReview)
        {
          leadResults = db.LeadResults
              .Join(db.LeadStatus, a => a.LeadID, b => b.LeadID, (a, b) => new { a, b })
              .Where(m => m.a.LeadID == m.b.LeadID && m.a.BlockId == m.b.BlockID && (m.b.LeadFlagsID==1))
              .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
              .Where(m => m.b.CallCentreID == introducerID)
              .Where(m => EntityFunctions.DiffDays(m.a.LeadDate,DateTime.Now)==0)
              .Select(m => m.a)
              .OfType<LeadResults>()
              .ToList();
        }
        else if (releaseOnly)
        {
          leadResults = db.LeadResults
             .Join(db.LeadStatus, a => a.LeadID, b => b.LeadID, (a, b) => new { a, b })
             .Where(m => m.a.LeadID == m.b.LeadID && m.a.BlockId == m.b.BlockID && (m.b.LeadFlagsID == 1))
             .Where(m => m.a.LeadID == viewModel.Leads.LeadID)
             .Where(m => m.b.CallCentreID == introducerID)
             .Select(m => m.a)
             .OfType<LeadResults>()
             .ToList();
        }
        else
        {
          leadResults = db.LeadResults
              .Join(db.LeadStatus, a => a.BlockId, b => b.BlockID, (a, b) => new { a, b })
              .Where(m => m.b.LeadFlagsID>=2 && m.a.LeadID == viewModel.Leads.LeadID && m.b.CallCentreID == introducerID)
              .Select(m => m.a)
              .OfType<LeadResults>()
              .ToList();
        }
        if (leadResults.Count()==0)
        {
          return PartialView("PartialShowLeads", viewModel);
        }
        if (!immediateReview && dayfilter == "7")
        {
          leadResults = (from lr in leadResults
                         join lr2 in leadResults on lr.BlockId equals lr2.BlockId
                         where lr.LeadDate >= DateTime.Now.AddDays(-7) 
                         select lr2)
                        .ToList();
        }
        if (!immediateReview && dayfilter == "1")
        {
          leadResults = (from lr in leadResults
                         join lr2 in leadResults on lr.BlockId equals lr2.BlockId
                         where lr.LeadDate >= DateTime.Now.AddDays(-1)
                         select lr2)
                        .ToList();
        }
        if (!immediateReview && leadref != "")
        {
          blockID=Convert.ToInt16(leadref);
          leadResults = (from lr in leadResults
                         join lr2 in leadResults on lr.BlockId equals lr2.BlockId
                         where lr.BlockId==blockID
                         select lr2)
                        .ToList();
        }
        if (!immediateReview && surname != "")
        {
          leadResults = (from lr in leadResults
                         join lr2 in leadResults on lr.BlockId equals lr2.BlockId
                         where lr.Question == "Surname" && lr.Answer.ToLower().Contains(surname.ToLower())
                         select lr2)
                        .ToList();
        }
        if (!immediateReview && telephone != "")
        {
          leadResults = (from lr in leadResults
                         join lr2 in leadResults on lr.BlockId equals lr2.BlockId
                         where (lr.Question == "Primary Telephone Number" && lr.Answer.Replace(" ","").Contains(telephone.Replace(" ",""))) ||
                          (lr.Question == "Mobile or Alternate Number" && lr.Answer.Replace(" ", "").Contains(telephone.Replace(" ", "")))
                         select lr2)
                        .ToList();
        }
        if (!immediateReview && postcode != "")
        {
          leadResults = (from lr in leadResults
                         join lr2 in leadResults on lr.BlockId equals lr2.BlockId
                         where lr.Question == "Postcode" && lr.Answer.ToLower() .Contains(postcode.ToLower())
                         select lr2)
                        .ToList();
        }
        if (!immediateReview && leadFilter == "Active")
        {
          leadResults = (from lr in leadResults
                         join ls in db.LeadStatus on lr.BlockId equals ls.BlockID
                         where ls.LeadFlag.Description != "Dead"
                         select lr)
                        .ToList();
        }
        if (!immediateReview && leadFilter == "Dead")
        {
          leadResults = (from lr in leadResults
                         join ls in db.LeadStatus on lr.BlockId equals ls.BlockID
                         where ls.LeadFlag.Description=="Dead"
                         select lr)
                         .ToList();
        }

        leadResults = leadResults.Distinct().ToList();
        blockID = 0;
        LeadStatus statusBlock = db.LeadStatus.FirstOrDefault();
        LeadFlags leadFlag = db.LeadFlags.FirstOrDefault();
        LeadReasons leadReason = db.LeadReasons.FirstOrDefault();
        viewModel.FullListLeadResults = new List<ListLeadResults>();
        testrecs = leadResults.Count();
        int totalLeads = 0;
        if (leadResults.Count()>0)
      	{
          viewModel.LeadDate = leadResults.LastOrDefault().LeadDate;
          foreach (LeadResults item in leadResults.OrderBy(m => m.BlockId).ThenBy(m => m.DisplayOrder))
          {
            ListLeadResults listLeadResults = new ListLeadResults();
            listLeadResults.LeadResult = item;
            if (item.BlockId != blockID)
            {
              statusBlock = db.LeadStatus
                  .Where(m => m.LeadID == item.LeadID && m.BlockID == item.BlockId)
                  .FirstOrDefault();
              leadFlag = db.LeadFlags.Find(statusBlock.LeadFlagsID);
              if (statusBlock.QCLeadReasonsID != null && statusBlock.QCLeadReasonsID > 1)
              {
                leadReason = db.LeadReasons.Find(statusBlock.QCLeadReasonsID);
              }
              else
              {
                leadReason = db.LeadReasons.Find(statusBlock.LeadReasonsID);
              }

              totalLeads++;
            }
            blockID = item.BlockId;
            listLeadResults.LeadStatus = statusBlock;
            listLeadResults.LeadFlag = leadFlag;
            listLeadResults.LeadReason = leadReason;

            viewModel.FullListLeadResults.Add(listLeadResults);
          }
        }
        viewModel.Titles = new List<string>();

        if (viewModel.FullListLeadResults.Count() > 0)
        {
          int questionCounter = 0;
          blockID = leadResults.FirstOrDefault().BlockId;
          List<LeadResults> lr = leadResults.Where(m => m.BlockId == blockID).OrderBy(m => m.DisplayOrder).ToList();
          foreach (var item in lr)
          {
            viewModel.Titles.Add(item.Question);
            questionCounter++;
            if (questionCounter == item.QuestionBlock)
            {
              questionCounter = 0;
              break;
            }
          }
        }

        ViewBag.TotalLeads = totalLeads;
        return PartialView("PartialShowLeads", viewModel);
      }
      catch (Exception e)
      {
        ViewBag.ErrorMessage = "Showing Leads " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException + " - num of recs=" + testrecs.ToString();
        return View("Errormessages");
      }

    }

    public ActionResult CallCentreStats()
    {
        int callcentreid = GetID();
        return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fAdministrator%2fdunsmore%2fCallCentreStats&rs:Command=Render&c=" + callcentreid.ToString());
        //return RedirectToAction("ShowPDF", new { callCentreID = callcentreid, pdfname = pdfName, specificReport = 1 });
    }

    public ActionResult ClientAgentstats()
    {
      int callcentreid = GetID();
      CallCentres callCentre = db.CallCentres.Find(callcentreid);
      string pdfName = callCentre.CallCentre;
      return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fAdministrator%2fdunsmore%2fClientAgentStats&rs:Command=Render&c=" + callcentreid.ToString());
      //return RedirectToAction("ShowPDF", new { callCentreID = callcentreid, pdfname = pdfName, specificReport=2 });
    }

    public ActionResult Tracker()
    {
      int callcentreid = GetID();
      return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fAdministrator%2fdunsmore%2fOutsourcerTracker&rs:Command=Render&c=" + callcentreid.ToString());
      //return RedirectToAction("ShowPDF", new { callCentreID = callcentreid, pdfname = pdfName, specificReport = 1 });
    }

    public ActionResult CCstats()
    {
        int callcentreid = GetID();
        return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fAdministrator%2fdunsmore%2fCCstats&rs:Command=Render&c=" + callcentreid.ToString());
        //return RedirectToAction("ShowPDF", new { callCentreID = callcentreid, pdfname = pdfName, specificReport = 1 });
    }

    public ActionResult ReturnStats()
    {
        int callcentreid = GetID();
        return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2fAdministrator%2fdunsmore%2fReturnAnalysisByCallCentre&rs:Command=Render&c=" + callcentreid.ToString());
        //return RedirectToAction("ShowPDF", new { callCentreID = callcentreid, pdfname = pdfName, specificReport = 1 });
    }

    public ActionResult PurchaseOrderReport(string pid)
    {
        int callcentreid = GetID();
        return RedirectToAction("ShowPDF", new { callCentreID = callcentreid, pdfname = "PurchaseOrder_"+pid, specificReport = 3 });
    }

    [System.Web.Mvc.OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    public FileStreamResult ShowPDF(string callCentreID="1", string pdfname="test", int specificReport=1, string pid="")
    {
      try
      {
      // Create a new proxy to the web service
      rsExecService.ReportExecutionService rsExec = new rsExecService.ReportExecutionService();
      // Authenticate to the web service using windows credentials
      rsExec.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["UserID"], ConfigurationManager.AppSettings["Pwd"]);
      // Load the selected report
      switch (specificReport)
      {
        case 1:
          rsExec.LoadReport("/dunsmore/CallCentreStats", null);
          break;
        case 2:
          rsExec.LoadReport("/dunsmore/ClientAgentStats", null);
          break;
        case 3:
          rsExec.LoadReport("/dunsmore/PurchaseOrder", null);
          break;
        default:
          break;
      }
      

      // Prepare Render arguments
      string encoding = String.Empty;
      string mimeType = String.Empty;
      string extension = String.Empty;
      rsExecService.Warning[] warnings = null;
      string[] streamIDs = null;

      // Prepare report parameters.
      rsExecService.ParameterValue[] parameters = new rsExecService.ParameterValue[1];
      parameters[0] = new rsExecService.ParameterValue();
      parameters[0].Value = callCentreID; 
      parameters[0].Name = "c";
      if (specificReport==3)
      {
        parameters[1] = new rsExecService.ParameterValue();
        parameters[1].Value = pid; 
        parameters[1].Name = "c";
      }

      // Set the parameters for the report needed.
      rsExec.SetExecutionParameters(parameters, "en-us");

      //Render the report to a byte[]
      Byte[] byteInfo = rsExec.Render("PDF", null, out extension, out encoding, out mimeType, out warnings, out streamIDs);

      // Return the report as a file stream
      System.IO.MemoryStream ms = new System.IO.MemoryStream();
      ms.Write(byteInfo, 0, byteInfo.Length);
      ms.Position = 0;

      HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + pdfname + ".pdf");

      return new FileStreamResult(ms, ConfigurationManager.AppSettings["ReportName"]);
      }
      catch (Exception e)
      {
        using (var ms=new MemoryStream())
        {
          using (StreamWriter sw = new StreamWriter(ms, Encoding.Unicode)) {
                sw.WriteLine("Enter Leads " + e.LineNumber().ToString() + " : " + e.Message);
            }
          return new FileStreamResult(ms, "application/text");
        }
      }

    }

    public ActionResult LoadingCapacity()
    {
      try
      {
      int callCentreID = GetID();
      
      LoadingCapacity loadingCapacity = db.LoadingCapacity.Where(m => m.CallCentreID == callCentreID).FirstOrDefault();
      
      DateTime weekBeginning=DateTime.Now;
      if (loadingCapacity == null)
      {
        weekBeginning = DateTime.Now.AddDays(8 - (int)DateTime.Now.DayOfWeek);
      }
      else 
      {
        weekBeginning = db.LoadingCapacity.Where(m => m.CallCentreID == callCentreID).OrderByDescending(m => m.WeekBeginning).Select(m => m.WeekBeginning).FirstOrDefault();
        weekBeginning = weekBeginning.AddDays(7);
      }
      if (loadingCapacity == null || weekBeginning < DateTime.Now.AddDays(49))
      {
        for (int i = 0; i < 8; i++)
        {
          loadingCapacity = new LoadingCapacity();
          loadingCapacity.CallCentreID = callCentreID;
          loadingCapacity.WeekBeginning = weekBeginning;
          db.LoadingCapacity.Add(loadingCapacity);
          weekBeginning = weekBeginning.AddDays(7);
        }
      }
      db.SaveChanges();

      List < LoadingCapacity > listLoadingCapacity= db.LoadingCapacity.Where(m => m.CallCentreID == callCentreID).ToList();

      return View(listLoadingCapacity);
      }
      catch (Exception e)
      {
        ViewBag.ErrorMessage = "Loading Capacity " + e.LineNumber().ToString() + " : " + e.Message + " - " + e.InnerException;
        return View("Errormessages");
      }
    }

    [HttpPost]
    public ActionResult LoadingCapacity(List<LoadingCapacity> listLoadingCapacity)
    {
      foreach (var item in listLoadingCapacity)
      {
        LoadingCapacity lC = db.LoadingCapacity.Find(item.LoadingCapacityID);
        lC.Capacity = item.Capacity;
        db.Entry(lC).State = EntityState.Modified;
      }
      db.SaveChanges();
      return RedirectToAction("Index","Home");
    }

    public string CheckDuplicate(string telephoneNumber)
    {
        telephoneNumber = telephoneNumber.Replace(" ", "");
        int telephoneRecs = db.LeadResults.Where(m => m.Question.ToLower().IndexOf("landline")!=-1 && m.Answer.Replace(" ", "") == telephoneNumber).Count();
            
        if (telephoneRecs>0)
        {
            return "Regret to inform you that we already have this number in the system - this must be a duplicate";
        }
        else
        {
            // Check number format by pattern matching
            if (telephoneNumber.Trim().Length<10)
            {
                return "Regret to inform you that this number appears to be invalid.";
            }
            return string.Empty;
        }
    }

    public string CheckPostcode(string postCode, string leadID)
    {
      if (postCode!=null)
      {
        try
        {
          postCode = postCode.Replace(" ", string.Empty);
          string AlphaPostCode = string.Empty;
          char[] postcodeArray = postCode.ToCharArray();
          foreach (var item in postcodeArray)
          {
            if (char.IsLetter(item))
            {
              AlphaPostCode += item.ToString();
            }
            else
            {
              break;
            }
          }

          string[] Territory = db.Leads.Find(Convert.ToInt16(leadID)).Territory.Split(',');

          if (Array.IndexOf(Territory,AlphaPostCode.ToUpper()) < 0)
          {
            foreach (var item in postcodeArray)
            {
              if (char.IsNumber(item))
              {
                AlphaPostCode += item.ToString();
              }
            }
            foreach (var item in Territory)
            {
              if (item.Any(char.IsDigit) && AlphaPostCode.Substring(0,item.Length).ToUpper()==item)
              {
                return string.Empty;
              }
            }
          }
          else
          {
            return string.Empty;
          }
      }
      catch (Exception)
      {
        return "OutOfTerritory";
      }
      }
      return "OutOfTerritory";
    }

    public static string StreetviewLatLong(int leadStatusID)
    {
      DunsmoreContext db = new DunsmoreContext();
      LeadStatus leadStatus = db.LeadStatus.Find(leadStatusID);
      string postCode = db.LeadResults
          .Where(m => m.LeadID == leadStatus.LeadID && m.BlockId == leadStatus.BlockID && m.Question == "Postcode")
          .Select(m => m.Answer)
          .FirstOrDefault();
      PostCodes postCodes = db.Postcodes.Where(m => m.Postcode == postCode.Replace(" ", "")).FirstOrDefault();
      string returnString = postCodes.lat.ToString() + "," + postCodes.longitude.ToString();
      return returnString;
    }

    public static string StreetviewPostcode(int leadStatusID)
    {
      DunsmoreContext db = new DunsmoreContext();
      LeadStatus leadStatus = db.LeadStatus.Find(leadStatusID);
      string postCode = db.LeadResults
          .Where(m => m.LeadID == leadStatus.LeadID && m.BlockId == leadStatus.BlockID && m.Question == "Postcode")
          .Select(m => m.Answer)
          .FirstOrDefault();
      PostCodes postCodes = db.Postcodes.Where(m => m.Postcode == postCode.Replace(" ", "")).FirstOrDefault();
      string returnString = postCode;
      return returnString;
    }

    public ViewModelOutsourcer ProcessQuestionnaire(ViewModelOutsourcer viewModel)
    {
      int callCentreID=0;
      if (viewModel.PreviewMode==false)
      {
        callCentreID=GetID();
      }

      viewModel.Leads = db.Leads.Where(m => m.LeadID == viewModel.LeadClient).FirstOrDefault();
      if (false && viewModel.Leads.StreetView == true)
      {
        string companyPostcode = viewModel.Leads.Company.Postcode.Replace(" ", "");
        PostCodes postCode = db.Postcodes.Where(m => m.Postcode == companyPostcode).FirstOrDefault();
        ViewBag.LatLong = string.Format("{0},{1}", postCode.lat.ToString(), postCode.longitude.ToString());
      }

      if (viewModel.PreviewMode == false)
      {
        ViewBag.LeftToSupply = db.PurchaseOrders
          .Where(m => m.LeadID == viewModel.LeadClient)
          .Where(m => m.Visible == true)
          .Where(m => m.CallCentreID == callCentreID)
          .Where(m => m.Paid == null || m.Paid == false)
          .Select(m => m.Deficit).Sum().ToString();
      }
      else
      {
        ViewBag.LeftToSupply = 0;
      }
      viewModel.ListCompanyRegistered = db.CompanyRegistered.Where(c => c.CompanyID == viewModel.Leads.CompanyID).ToList();
      viewModel.ListCompanyRestrictions = db.CompanyRestriction.Where(c => c.CompanyID == viewModel.Leads.CompanyID).ToList();
      viewModel.ListCompanySundries = db.CompanySundries.Where(c => c.CompanyID == viewModel.Leads.CompanyID).ToList();
      viewModel.LeadTemplate = db.LeadTemplate.Where(c => c.LeadTemplateID == viewModel.Leads.LeadTemplateID).FirstOrDefault();
      viewModel.ListLeadStat = db.LeadStat.Where(l => l.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
      viewModel.ListLeadGroups = db.LeadGroups.Where(l => l.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
      viewModel.ListStatQuestions = db.LeadStatQuestions.Include(i => i.LeadStat).Where(w => w.LeadStat.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
      viewModel.ListGroupQuestions = db.LeadGroupQuestions.Include(i => i.LeadGroups).Where(w => w.LeadGroups.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID).ToList();
      viewModel.LeadQuestions = new List<questiontype>();
      int questionRow = 0;
      questiontype newQs;
      int questionOrder = 1;
      while (questionOrder != 99)
      {
        // Static Question Set ?
        if (db.LeadStat.Any(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder))
        {
          LeadStat item = db.LeadStat.Where(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder).FirstOrDefault();
          newQs = new questiontype();
          newQs.QuestionRow = questionRow;
          newQs.TheQuestion = string.Empty;
          newQs.TheAnswer = string.Empty;
          newQs.Mandatory = false;
          newQs.IsQuestionHeader = true;
          newQs.QuestionHeader = item.Title;
          newQs.Notes = item.Notes;
          newQs.DisplayOrder = item.DisplayOrder * 100;
          viewModel.LeadQuestions.Add(newQs);
          questionRow++;
          foreach (var statitem in viewModel.ListStatQuestions.Where(m => m.LeadStatID == item.LeadStatID).OrderBy(m => m.DisplayOrder))
          {
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = statitem.Question;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = statitem.Mandatory;
            newQs.QuestionType = statitem.AnswerType;
            newQs.Notes = statitem.Notes;
            newQs.AcceptedAnswerChar = statitem.AcceptedAnswerChar;
            newQs.AcceptedAnswerBool = statitem.AcceptedAnswerBool;
            newQs.AcceptedAnswerIntFrom = statitem.AcceptedAnswerIntFrom;
            newQs.AcceptedAnswerIntTo = statitem.AcceptedAnswerIntTo;
            newQs.LeadStatQuestionsID = statitem.LeadStatQuestionsID;
            newQs.DropDown = statitem.DropDown;
            newQs.DisplayOrder = item.DisplayOrder * 100 + statitem.DisplayOrder;
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
          }
          questionRow++;
        }
        else if (db.LeadGroups.Any(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder))
        {
          LeadGroups item = db.LeadGroups.Where(m => m.LeadTemplateID == viewModel.LeadTemplate.LeadTemplateID && m.QuestionOrder == questionOrder).FirstOrDefault();
          newQs = new questiontype();
          newQs.QuestionRow = questionRow;
          newQs.TheQuestion = string.Empty;
          newQs.TheAnswer = string.Empty;
          newQs.Mandatory = false;
          newQs.IsQuestionHeader = true;
          newQs.QuestionHeader = item.Title;
          newQs.QualifyingGroup = item.QualifyingGroup;
          newQs.MinMandatoryPrimary = item.MinMandatoryPrimary;
          newQs.MinMandatorySecondary = item.MinMandatorySecondary;
          newQs.LeadGroupsID = item.LeadGroupsID;
          newQs.Notes = item.Notes;
          newQs.DisplayOrder = item.DisplayOrder * 100;
          if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
          {
            newQs.SubHeader = "Two groups here. So we need at least " + item.MinMandatoryPrimary.ToString() + " in this group, and ...";
          }
          else if (item.MinMandatoryPrimary > 0)
          {
            newQs.SubHeader = "We need at least " + item.MinMandatoryPrimary.ToString() + " in this group to qualify.";
          }
          viewModel.LeadQuestions.Add(newQs);
          questionRow++;
          // Primary Group
          foreach (var groupitem in viewModel.ListGroupQuestions.Where(m => m.LeadGroupsID == item.LeadGroupsID).Where(m => m.PrimarySecondary == "P").OrderBy(m => m.DisplayOrder))
          {
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = groupitem.Question;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = groupitem.Mandatory;
            newQs.QuestionType = groupitem.AnswerType;
            newQs.Notes = groupitem.Notes;
            newQs.DropDown = groupitem.DropDown;
            newQs.AcceptedAnswerChar = groupitem.AcceptedAnswerChar;
            newQs.AcceptedAnswerBool = groupitem.AcceptedAnswerBool;
            newQs.AcceptedAnswerIntFrom = groupitem.AcceptedAnswerIntFrom;
            newQs.AcceptedAnswerIntTo = groupitem.AcceptedAnswerIntTo;
            newQs.LeadGroupQuestionsID = groupitem.LeadGroupQuestionsID;
            newQs.DropDown = groupitem.DropDown;
            newQs.PrimarySecondary = "P";
            newQs.LeadGroupsID = item.LeadGroupsID;
            newQs.QualifyingGroup = item.QualifyingGroup;
            newQs.DisplayOrder = item.DisplayOrder * 100 + groupitem.DisplayOrder;
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
          }
          if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
          {
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = string.Empty;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = false;
            newQs.IsQuestionHeader = true;
            newQs.QuestionHeader = item.Title;
            if (item.MinMandatoryPrimary > 0 && item.MinMandatorySecondary > 0)
            {
              newQs.SubHeader = "... at least " + item.MinMandatorySecondary.ToString() + " in this group to qualify.";
            }
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
          }
          // Secondary Group
          foreach (var groupitem in viewModel.ListGroupQuestions.Where(m => m.LeadGroupsID == item.LeadGroupsID).Where(m => m.PrimarySecondary == "S").OrderBy(m => m.DisplayOrder))
          {
            newQs = new questiontype();
            newQs.QuestionRow = questionRow;
            newQs.TheQuestion = groupitem.Question;
            newQs.TheAnswer = string.Empty;
            newQs.Mandatory = groupitem.Mandatory;
            newQs.QuestionType = groupitem.AnswerType;
            newQs.Notes = groupitem.Notes;
            newQs.DropDown = groupitem.DropDown;
            newQs.PrimarySecondary = "S";
            newQs.AcceptedAnswerChar = groupitem.AcceptedAnswerChar;
            newQs.AcceptedAnswerBool = groupitem.AcceptedAnswerBool;
            newQs.AcceptedAnswerIntFrom = groupitem.AcceptedAnswerIntFrom;
            newQs.AcceptedAnswerIntTo = groupitem.AcceptedAnswerIntTo;
            newQs.LeadGroupQuestionsID = groupitem.LeadGroupQuestionsID;
            newQs.LeadGroupsID = item.LeadGroupsID;
            newQs.QualifyingGroup = item.QualifyingGroup;
            newQs.DisplayOrder = item.DisplayOrder * 100 + groupitem.DisplayOrder;
            viewModel.LeadQuestions.Add(newQs);
            questionRow++;
          }
          questionRow++;
        }
        else
        {
          questionOrder = 98;
        }
        questionOrder++;
      }
      foreach (var item in viewModel.ListCompanyRegistered)
      {
        newQs = new questiontype();
        newQs.QuestionRow = questionRow;
        newQs.TheQuestion = item.LeadQuestion;
        newQs.TheAnswer = string.Empty;
        newQs.Mandatory = item.MandatoryLeadQuestion;
        newQs.QuestionType = "L";
        newQs.Notes = item.Notes;
        newQs.CompanyRegisteredID = item.CompanyRegisteredID;
        viewModel.LeadQuestions.Add(newQs);
        questionRow++;
      }
      foreach (var item in viewModel.ListCompanyRestrictions)
      {
        newQs = new questiontype();
        newQs.QuestionRow = questionRow;
        newQs.TheQuestion = item.LeadQuestion;
        newQs.TheAnswer = string.Empty;
        newQs.Mandatory = item.MandatoryLeadQuestion;
        newQs.QuestionType = "L";
        newQs.Notes = item.Notes;
        newQs.CompanyRestrictionsID = item.CompanyRestrictionsID;
        viewModel.LeadQuestions.Add(newQs);
        questionRow++;
      }
      if (viewModel.ListCompanySundries.Count() > 0)
      {
        newQs = new questiontype();
        newQs.QuestionRow = questionRow;
        newQs.TheQuestion = string.Empty;
        newQs.TheAnswer = string.Empty;
        newQs.Mandatory = false;
        newQs.IsQuestionHeader = true;
        newQs.QuestionHeader = "Client Specific Questions";
        viewModel.LeadQuestions.Add(newQs);
        questionRow++;
        foreach (var item in viewModel.ListCompanySundries)
        {
          newQs = new questiontype();
          newQs.QuestionRow = questionRow;
          newQs.TheQuestion = item.LeadQuestion;
          newQs.TheAnswer = string.Empty;
          newQs.Mandatory = item.MandatoryLeadQuestion;
          newQs.QuestionType = "L";
          newQs.CompanySundriesID = item.CompanySundriesID;
          viewModel.LeadQuestions.Add(newQs);
          questionRow++;
        }
      }

      return viewModel;
    }

    public ActionResult AssignIntroducer()
    {
      ViewBag.UserID = new SelectList(db.Users.OrderBy(m => m.UserName), "UserID", "UserName");
      ViewBag.CallCentreID = db.CallCentres
            .Where(m => m.Category=="I")
            .OrderBy(m => m.potitle)
            .ToList()
                .Select(c => new SelectListItem
                {
                    Value = c.CallCentreID.ToString(),
                    Text = c.potitle
                });

      return View();
    }

    [HttpPost]
    public ActionResult AssignIntroducer(IntroducerUsers introducerUser)
    {
      if (ModelState.IsValid)
      {
        db.IntroducerUsers.Add(introducerUser);
        db.SaveChanges();
      }

      return RedirectToAction("Index");
    }

    public ActionResult AssignInstaller()
    {
      ViewBag.UserID = new SelectList(db.Users.OrderBy(m => m.UserName), "UserID", "UserName");
      ViewBag.CallCentreID = db.CallCentres
            .Where(m => m.Category == "N")
            .OrderBy(m => m.potitle)
            .ToList()
                .Select(c => new SelectListItem
                {
                  Value = c.CallCentreID.ToString(),
                  Text = c.potitle
                });

      return View();
    }

    [HttpPost]
    public ActionResult AssignInstaller(Installers installer)
    {
      if (ModelState.IsValid)
      {
        db.Installers.Add(installer);
        db.SaveChanges();
      }

      return RedirectToAction("Index");
    }

    public ActionResult ViewReleaseToClient()
    {
      return RedirectToAction("Index");
    }

    public JsonResult DeleteLead(int blockID)
    {
      foreach (var item in db.LeadResults.Where(m => m.BlockId==blockID))
      {
        db.LeadResults.Remove(item);
      }
      LeadStatus ls=db.LeadStatus.Where(m => m.BlockID == blockID).FirstOrDefault();
      db.Earnt.Remove(db.Earnt.Where(m => m.LeadStatusID == ls.LeadStatusID).FirstOrDefault());
      db.LeadStatus.Remove(ls);
      db.SaveChanges();
      return Json(true);
    }

    public static string GetColourCode(LeadFlags leadFlag)
    {
      string colourCode;
      if (leadFlag.Description=="Dead")
      {
        colourCode = "535253";
      }
      else
      {
        colourCode = "000000";
      }

      return "color: #" + colourCode + ";";
    }

    public ActionResult ShowCampaigns()
    {
      return View();
    }

    public ActionResult ByStatus()
    {
      int callcentreid = GetID();
      Guid logon=db.CallCentres.Find(callcentreid).LogOn;
      return Redirect("http://webellas.arvixevps.com/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2forac%2flye%2fByStatus&rs:Command=Render&cc=" + logon);
    }

    // new method here
  }
}
